package com.renwei.yunlong.fragment;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.activity.CommonSearchActivity;
import com.renwei.yunlong.activity.news.MessageDealActivity;
import com.renwei.yunlong.activity.news.StartChatActivity;
import com.renwei.yunlong.adapter.NewsMsgAdapter;
import com.renwei.yunlong.base.BaseLazyFragment;
import com.renwei.yunlong.bean.CommonBean;
import com.renwei.yunlong.bean.MsgBean;
import com.renwei.yunlong.event.MessageRefreshEvent;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.view.SearchImage;
import com.renwei.yunlong.view.SimpleOptionView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zyf.fwms.commonlibrary.base.baseadapter.BaseRecyclerViewAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import de.greenrobot.event.EventBus;
import io.rong.imkit.RongIM;
import io.rong.imkit.userInfoCache.RongUserInfoManager;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.UserInfo;

/**
 * 消息--Fragment
 * <p>
 * Created by Administrator on 2017/8/24.
 */

public class NewsFragment extends BaseLazyFragment implements HttpTaskListener {


    public static final int MESSAGE_DELETE = 0;
    public static final int MESSAGE_READ = 1;
    public static final int MESSAGE_UNREAD = 2;
    @Bind(R.id.simpleTileView)
    SimpleOptionView simpleTileView;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.search_image)
    SearchImage searchImage;
    private NewsMsgAdapter adapter;

    private List<MsgBean.RowsBean> list = new ArrayList<>();
    private int count;
    private List<MsgBean.RowsBean> mLocaList;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_news;
    }

    @Override
    public void onLazyLoad() {
        simpleTileView.setLeftImageViewVisibility(View.INVISIBLE);
        simpleTileView.setTitle("消息");
        simpleTileView.setRightOption(R.mipmap.plus, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StartChatActivity.openActivity(getContext(), null);
            }
        });

        refreshLayout.setEnableLoadmore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {

                refresh(true);
            }
        });
        searchImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonSearchActivity.OpenActivityFromMessage(getActivity(), view, NewsFragment.class);
            }
        });

        adapter = new NewsMsgAdapter(getContext());
        adapter.setOnItemClickLitener(new BaseRecyclerViewAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                MsgBean.RowsBean bean = adapter.getItem(position);
                switch (view.getId()) {
                    case R.id.btn_delete:
                        updateMessage(bean.getType(), NewsFragment.MESSAGE_DELETE);
                        break;
                    case R.id.btn_read:
                        if (bean.getQuantity() != 0) {
                            LogUtil.e("点击开始时间 = "+System.currentTimeMillis());
                            updateMessage(bean.getType(), NewsFragment.MESSAGE_READ);
                        } else {
                            updateMessage(bean.getType(), NewsFragment.MESSAGE_UNREAD);
                        }
                        break;
                    default:
                        itemClick(bean, position);
                        break;

                }
            }

            private void itemClick(MsgBean.RowsBean bean, int position) {
                if (TextUtils.isEmpty(bean.getType())) {
                    Conversation conversation = bean.getConversation();
                    String title = "";
                    String targetId = conversation.getTargetId();
                    Conversation.ConversationType type = conversation.getConversationType();
                    if (conversation.getConversationType() == Conversation.ConversationType.GROUP) {
                        Group group = RongUserInfoManager.getInstance().getGroupInfo(targetId);
                        if (group != null) {
                            title = group.getName();
                        }
                        RongIM.getInstance().startConversation(getContext(), type, targetId, title);
                    } else if (conversation.getConversationType() == Conversation.ConversationType.PRIVATE) { //单聊
                        UserInfo userInfo = RongUserInfoManager.getInstance().getUserInfo(targetId);
                        if (userInfo != null) {
                            title = userInfo.getName();
                        }
                        RongIM.getInstance().startConversation(getContext(), type, targetId, title);
                    }
                    if (conversation.getUnreadMessageCount() != 0) {
                        conversation.setUnreadMessageCount(0);
                        adapter.notifyItemChanged(position);
                    }
                } else {
                    if ("7".equals(bean.getType().substring(0, 1))) { //企业申请
                    } else {
                        MessageDealActivity.OpenActivity(getContext(), bean.getType(), "");
                    }
                }
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(adapter);

        refresh(true);
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 100: //站内消息
                    count++;
                    if (mLocaList==null){
                        mLocaList = (List<MsgBean.RowsBean>) msg.obj;
                    }
                    list.addAll(mLocaList);
                    break;
                case 200: // 聊天消息
                    count++;
                    list.addAll(0, (List<MsgBean.RowsBean>) msg.obj);
                    break;
                default:
                    break;

            }
            if (count == 2) {
                refreshLayout.finishRefresh();
                adapter.setData(list);
                for (MsgBean.RowsBean rowsBean : list) {
                    Conversation conversation = rowsBean.getConversation();
                    if (conversation != null && "1".equals(conversation.getTargetId())) {
                        return;
                    }
                }
                // 添加客服
                MsgBean.RowsBean cService = new MsgBean.RowsBean();
                Conversation cSconversation = new Conversation();
                cSconversation.setConversationType(Conversation.ConversationType.PRIVATE);
                cSconversation.setTargetId("1");
                cService.setConversation(cSconversation);
                adapter.addLastData(cService);
            }
        }
    };

    public void initData() {
        // 获取聊天消息
        RongIM.getInstance().getConversationList(new RongIMClient.ResultCallback<List<Conversation>>() {
            @Override
            public void onSuccess(List<Conversation> conversations) {
                List<MsgBean.RowsBean> list = new ArrayList<>();
                if (conversations != null) {
                    for (Conversation conversation : conversations) {
                        MsgBean.RowsBean bean = new MsgBean.RowsBean();
                        bean.setConversation(conversation);
                        list.add(bean);
                    }
                }
                handler.sendMessage(handler.obtainMessage(200, list));
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });

        if (mLocaList !=null){
            handler.sendMessage(handler.obtainMessage(100, null));
            return;
        }

        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {
            map.put("receiverCompanyCode", ownerBean.getRows().getOwnerCode());
            map.put("receiverId", ownerBean.getRows().getEmployeeId());
        } else if ("2".equals(companyType)) {
            map.put("receiverCompanyCode", serviceLoginBean.getRows().getServiceProviderCode());
            map.put("receiverId", serviceLoginBean.getRows().getEmployeeId());
        }
        ServiceRequestManager.getManager().getUnreadMsg(getContext(), JsonMapUtil.mapToJson(map), this);
    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 1: //消息列表
                MsgBean msgBean = new Gson().fromJson(result, MsgBean.class);
                if (msgBean.getMessage().getCode() == 200) {
                    int unReadCount = 0;
                    List<MsgBean.RowsBean> list = new ArrayList<>();
                    for (String key : msgBean.getRows().keySet()) {
                        MsgBean.RowsBean rowsBean = msgBean.getRows().get(key);
                        rowsBean.setType(key);
                        list.add(rowsBean);
                        unReadCount += rowsBean.getQuantity();
                    }
                    handler.sendMessage(handler.obtainMessage(100, list));
                    EventBus.getDefault().post(new MessageRefreshEvent(unReadCount + ""));
                } else {
                    showCenterInfoMsg(msgBean.getMessage().getMessage());
                }
                break;
            case 2: //删除或已读
                CommonBean commonBean = new Gson().fromJson(result, CommonBean.class);
                if (commonBean.getMessage().getCode() == 200) {
                    refresh(true);
                } else {
                    showCenterInfoMsg(commonBean.getMessage().getMessage());
                }
                break;
        }

    }

    @Override
    public void onException(int requestId, String code) {
    }


    //endregion

    /**
     *  由于刷新本地消息数据过大时  会卡顿
     * @param b 判断是否全部刷新 true本地和聊天消息都刷新
     *          false  则只刷新聊天消息
      */
    public void refresh(boolean b) {
        if (b){
            mLocaList =null;
        }

        if (adapter != null) {
            count = 0;
            list.clear();
            initData();
        }
    }

    // 更新消息状态
    private void updateMessage(String type, int flag) {
        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {
            map.put("receiverCompanyCode", ownerBean.getRows().getOwnerCode());
            map.put("receiverId", ownerBean.getRows().getEmployeeId());
        } else {
            map.put("receiverCompanyCode", serviceLoginBean.getRows().getServiceProviderCode());
            map.put("receiverId", serviceLoginBean.getRows().getEmployeeId());
        }
        map.put("type", type);
        map.put("deleteFlag", flag + "");
        ServiceRequestManager.getManager().updateMessageFlag(getContext(), JsonMapUtil.mapToJson(map), this);
    }
}
